﻿using System;
using System.Windows.Controls;
using System.Windows.Threading;
using CodeIn.Ui;
using CodeIn.Ui.Dock;

namespace CodeIn.Ui {
	public static class UiHelper {
		/// <summary>
		/// Creates a panel from the given build action. The buildAction must
		/// return a ContentControl. This control will be the main content of the panel.
		/// </summary>
		public static PanelViewModel CreatePanel(string title, Func<ContentControl> buildAction) {
			PanelViewModel ret = new PanelViewModel(title, null);
			App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(() => {
				ret.Body = buildAction();
			}));
			return ret;
		}

		/// <summary>
		/// Adds a panel to the main UI, on the requested side.
		/// </summary>
		public static void ShowPanel(PanelViewModel panel, PanelSide side) {
			App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(() => {
				if (PanelRequested != null)
					PanelRequested(null, new PanelRequestedEventArgs(panel, side));
			}));
		}

		/// <summary>
		/// Synchronizes an action with the main Ui thread. This is just a wrapper
		/// around App.Current.Dispatcher.BeginInvoke. You can use it directly if needed.
		/// </summary>
		public static void Synchronize(Action action) {
			if (App.Current != null) {
				App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(() => {
					action();
				}));
			}
		}

		/// <summary>
		/// Synchronizes an action with the main Ui thread. This is just a wrapper
		/// around App.Current.Dispatcher.BeginInvoke. You can use it directly if needed.
		/// </summary>
		public static void Synchronize(Action<object> action, object param) {
			if (App.Current != null) {
				App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Render, new Action<object>(p => {
					action(p);
				}), param);
			}
		}

		/// <summary>
		/// Combines the effects of CreatePanel() and ShowPanel().
		/// </summary>
		public static PanelViewModel CreateAndShowPanel(string title, PanelSide side, Func<ContentControl> buildAction) {
			var panel = CreatePanel(title, buildAction);
			ShowPanel(panel, side);
			return panel;
		}

		public static event EventHandler<PanelRequestedEventArgs> PanelRequested;
		public class PanelRequestedEventArgs : EventArgs {
			public PanelViewModel PanelViewModel { get; set; }
			public PanelSide Side { get; set; }
			public PanelRequestedEventArgs(PanelViewModel panel, PanelSide side) {
				PanelViewModel = panel;
				Side = side;
			}
		}
	}
}
